package com.yricky.poetcard.harmony;

import com.yricky.jinrishici.PoetModel;
import com.yricky.poetcard.MyApplication;
import com.yricky.poetcard.harmony.slice.UIAbilitySlice;
import ohos.aafwk.ability.*;
import ohos.aafwk.content.Intent;
import ohos.utils.zson.ZSONObject;

public class UIAbility extends Ability {
    private static final int DEFAULT_DIMENSION_2X2 = 2;
    private static final int DIMENSION_1X2 = 1;
    private static final int DIMENSION_4X4 = 4;
    private static final int DIMENSION_2X4 = 3;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(UIAbilitySlice.class.getName());
    }

    @Override
    protected ProviderFormInfo onCreateForm(Intent intent) {

        ProviderFormInfo formInfo = new ProviderFormInfo();
        SharedPreferences sp=SharedPreferences.getInstance(this);

        long id=(long)intent.getParams().getParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY);

        String formName = intent.getStringParam(AbilitySlice.PARAM_FORM_NAME_KEY);
        int dimension = intent.getIntParam(AbilitySlice.PARAM_FORM_DIMENSION_KEY, DEFAULT_DIMENSION_2X2);
        sp.syncValue("card"+id,""+dimension);
        if (formName.equals("service_widget")) {
            formInfo.setJsBindingData(getFormData(dimension));
        }


        return formInfo;
    }

    @Override
    protected void onCastTempForm(long formId) {
        super.onCastTempForm(formId);
    }

    @Override
    protected void onDeleteForm(long formId) {
        super.onDeleteForm(formId);
        SharedPreferences sp=SharedPreferences.getInstance(this);
        sp.deleteValue("card"+formId);
    }

    @Override
    protected void onUpdateForm(long formId) {
        super.onUpdateForm(formId);
        SharedPreferences sp=SharedPreferences.getInstance(this);
        String dim;
        if((dim=sp.syncValue("card"+formId,null))!=null){
            try {
                updateForm(formId,getFormData(Integer.parseInt(dim)));
            } catch (FormException e) {
                e.printStackTrace();
            }
        }
    }

    public FormBindingData getFormData(int size){

        PoetModel poetModel=((MyApplication)getAbilityPackage()).getPoetModel();
        poetModel.update(null);
        String poetJsonString = poetModel.getJSONString();

        ZSONObject zsonObject = ZSONObject.stringToZSON(poetJsonString);
        zsonObject.put("is2x2",size==DEFAULT_DIMENSION_2X2);
        return new FormBindingData(zsonObject);
    }


    @Override
    protected void onTriggerFormEvent(long formId, String message) {
        onUpdateForm(formId);
    }
}
